<template>
  <el-form label-width="80px">
    <el-divider content-position="center">选项</el-divider>
    <div class="mb10">
      <el-form-item label="数据来源">
        <el-select v-model="formData.type">
          <el-option
            v-for="(item, index) in fromOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </div>

    <div v-if="formData.type === 'LOCAL'">
      <el-form-item label="数据选项">
        <el-input
          v-model="formData.data"
          type="textarea"
          placeholder="JSON格式"
          rows="10"
          @input="inputData"
        />
      </el-form-item>
    </div>
    <div v-if="formData.type === 'INTERFACE'">
      <el-form-item label="接口地址">
        <el-input v-model="formData.api" placeholder="接口的地址必须是绝对地址" />
      </el-form-item>
    </div>
    <el-form-item label="属性key">
      <el-input v-model="formData.keyLabel" placeholder="属性key" />
    </el-form-item>
    <el-form-item label="属性value">
      <el-input v-model="formData.keyValue" placeholder="属性value" />
    </el-form-item>
  </el-form>
</template>
<script>
export default {
  name: 'Options',
  props: {
    config: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      formData: {},
      fromOptions: [
        { label: '本地数据', value: 'LOCAL' },
        { label: '接口获取', value: 'INTERFACE' }
      ]
    }
  },
  watch: {
    config () {
      this.getFormData()
    },
    formData: {
      deep: true,
      handler () {
        try {
          const { type, data } = this.formData
          const o = {
            ...this.formData,
            data: type === 'local' ? JSON.parse(data) : data
          }
          this.$emit('input', o)
        } catch (e) {
          this.$message.warning(`数据选项的JSON解析失败，请重试！`)
        }
      }
    }
  },
  created () {
    this.getFormData()
  },
  methods: {
    getFormData () {
      const {
        type = 'local',
        keyLabel = 'label',
        keyValue = 'value',
        api,
        data
      } = this.config.datas || {}
      this.formData = {
        type,
        keyLabel,
        keyValue,
        api,
        data: JSON.stringify(Array.isArray(data) ? data : [], null, '\t')
      }
    },
    inputData () {}
  }
}
</script>
<style lang="scss" scoped>
@import "~element-ui/packages/theme-chalk/src/common/var.scss";
.el-row {
  margin-bottom: 10px;
}
.sep {
  text-align: center;
  color: #999;
  margin-top: 5px;
}
.remove-options {
  cursor: pointer;
  color: $--color-danger;
  i {
    margin: 8px 0 0 10px;
  }
}
.add-options {
  cursor: pointer;
  color: $--color-primary;
}
</style>
